package com.retail.global.log;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.global.annon.TraceLog;
import com.retail.global.security.LoginUserUtil;
import com.retail.system.entity.request.LogRequest;
import com.retail.system.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Administrator
 */
@Aspect
@Component
@Slf4j
public class TraceLogSupport {

    private final LogService logService;

    public TraceLogSupport(LogService logService) {
        this.logService = logService;
    }

    @Pointcut("@annotation(com.retail.global.annon.TraceLog)")
    private void pointcut() {
    }

    @Before("pointcut()&&@annotation(traceLog)")
    public void before(JoinPoint joinPoint, TraceLog traceLog) {
        try {
            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (null == attributes) {
                throw new Exception();
            }
            HttpServletRequest request = attributes.getRequest();
            LogRequest log = new LogRequest();
            log.setUrl(request.getRequestURI());
            try {
                log.setUserId(LoginUserUtil.getUserId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                log.setUserName(LoginUserUtil.getPrincipal().getUsername());
            } catch (Exception e) {
                log.setUserName("");
                e.printStackTrace();
            }
            log.setIp(request.getRemoteHost());
            log.setClassName(joinPoint.getSignature().getDeclaringTypeName());
            log.setMethod(request.getMethod());
            log.setMethodName(joinPoint.getSignature().getName());
            try {
                log.setArgs(JSON.toJSONString(joinPoint.getArgs()));
            } catch (Exception e) {
                log.setArgs("");
            }
            log.setRemark("");
            log.setCreateTime(DateUtil.date());
            log.setDelFlag(DelFlagEnum.NO.getValue());
            log.setStatusFlag(StatusFlagEnum.USE.getValue());
            logService.save(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
